package com.example.demo.colltroller;

import com.example.demo.exception.BusinessException;
import com.example.demo.pojo.vo.*;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;
    //TODO restful风格的查询: get请求
    //TODO 这里有异常不捕获,等下统一处理
//    @PostMapping("/find")
//    public Result find(@RequestBody QueryPageBean queryPageBean){
//        PageResult page = service.selectByPage(queryPageBean);
//        return new Result(true,"查询成功!",page);
//    }
    //restful风格的查询: get请求
    @GetMapping("/find/{currentPage}/{pageSize}/{username}")
    public Result find(@PathVariable Integer currentPage,
                       @PathVariable Integer pageSize,
                       @PathVariable String username
    ){
        PageResult page = method01(currentPage, pageSize, username);
        return new Result(true,"查询成功!",page);
    }

    @GetMapping("/find/{currentPage}/{pageSize}")
    public Result find(@PathVariable Integer currentPage,
                       @PathVariable Integer pageSize
    ){
        PageResult page = method01(currentPage, pageSize, "");
        return new Result(true,"查询成功!",page);
    }

    private PageResult method01(@PathVariable Integer currentPage, @PathVariable Integer pageSize, @PathVariable String username) {
        QueryPageBean queryPageBean = new QueryPageBean();
        queryPageBean.setCurrentPage(currentPage);
        queryPageBean.setPageSize(pageSize);
        HashMap<String, String> queryParams = new HashMap<>();
        queryParams.put("username", username);
        queryPageBean.setQueryParams(queryParams);

        return service.findByPage(queryPageBean);
    }

    @PostMapping("/add")
    public Result add(@RequestBody AddUser au){
        service.addUser(au);
        return new Result(true,"添加成功!");
    }

    @PutMapping ("/update")
    public Result update(@RequestBody UpdateUser uu){
        service.updateUser(uu);
        return new Result(true,"修改成功!");
    }

    @DeleteMapping("/delete/{uid}")
    public Result delete(@PathVariable String uid){
        Integer id = Integer.parseInt(uid);
        if(id <= 0){
            throw new BusinessException("删除失败,id不能小于等于0!");
        }
        service.deleteUser(uid);
        return new Result(true,"删除成功!");
    }

}
